package services

import (
	"context"
	"gin-study/app/models"
	"github.com/gin-gonic/gin"
)

const CTX_KEY_RESPONSE = "responses"
const CTX_KEY_TRACE = "trace"
const CTX_KEY_USER = "user"

var Ctx = new(ctx)

type ctx struct {
}

func (this *ctx) SetUser(c *gin.Context, u *models.User) {
	c.Set(CTX_KEY_USER, u)
}

func (this *ctx) GetUser(c *gin.Context) *models.User {
	u, exists := c.Get(CTX_KEY_USER)
	if !exists {
		panic("找不到用户")
	}
	return u.(*models.User)
}

func (this *ctx) SetResponse(c *gin.Context, res interface{}) {
	c.Set(CTX_KEY_RESPONSE, res)
}

func (this *ctx) GetResponse(c *gin.Context) interface{} {
	res, exists := c.Get(CTX_KEY_RESPONSE)
	if !exists {
		return nil
	}
	return res
}

func (this *ctx) SetTraceCtx(c *gin.Context, data interface{}) {
	c.Set(CTX_KEY_TRACE, data)
}

func (this *ctx) GetTraceCtx(c *gin.Context) context.Context {
	data, exists := c.Get(CTX_KEY_TRACE)
	if !exists {
		panic("找不到跟踪上下文")
	}
	return data.(context.Context)
}
